package com.example.czy.utils;

import java.io.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 通用工具
 *
 * @Author czy
 * @Date 2023-12-11 01:01:12
 **/
public class CommUtils {
    /**
     * 深度复制
     *
     * @param object
     * @param <T>
     * @return
     */
    public static <T> T deepCopy(T object) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bos);
            out.writeObject(object);
            out.flush();
            out.close();

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInput in = new ObjectInputStream(bis);
            T copy = (T) in.readObject();
            return copy;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return object;
        }
    }


    /**
     * 分页
     *
     * @param list
     * @param pageNum  页码
     * @param pageSize 每页条数
     * @param <T>
     * @return
     */
    public static <T> List<T> getPage(List<T> list, int pageNum, int pageSize) {
        return list.stream()
                .skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
    }

    /**
     * 校验流水号是否符合规则
     * @param serial 流水号 0021
     * @param reportNo 流水号 E18-20230021-1
     * @return
     */
    public static boolean serialCheck(String serial, String reportNo) {
        // 编号规则
        String rule = "E18-2023#LSH证书报告编号#-1";

        // 流水号占位符
        String placeholder = "#LSH证书报告编号#";

        // 规则校验算法
        String[] split = rule.split(placeholder);
        String replace = reportNo;
        for (String s : split) {
            if (replace.indexOf(s) < 0) {
                replace = null;
                break;
            }
            replace = replace.replace(s, "");
        }

        return replace != null && replace.length() == serial.length();
    }

}
